<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组扁平化</title>
</head>

<body>

</body>
<script>
    // 1.flat()方法
    const arr = [1, [2, [3, [4]]], [5, 6]];
    // console.log(arr);
    // var arr_flat = arr.flat(Infinity);
    // console.log(arr_flat);


    // 2.递归处理
    function flatArr(arr, a) {
        let result = [];
        for (let i = 0; i < arr.length; i++) {
            if (a <= 0) {
                result.push(arr[i])
            } else {
                if (Array.isArray(arr[i])) {
                    result = result.concat(flatArr(arr[i], --a));
                } else {
                    result.push(arr[i]);
                }
            }
        }
        return result;
    }
    console.log(flatArr(arr, 2));

    // 3.用 reduce实现
    function myFlat(arr) {
        return arr.reduce((pre, cur) => {
            return pre.concat(Array.isArray(cur) ? myFlat(cur) : cur);
        }, [])
    }
    myFlat(arr)


    //4.用扩展运算符
    function flatten(arr) {
        while (arr.some(item => Array.isArray(item))) {
            arr = [].concat(...arr);
        }
        return arr;
    }


    // 5.toString实现flat方法
    var arr11 = [1, [2, 3, [4, 5]], [6, 7]];
    console.log(arr11.toString().split(',').map(item => 1 * item));

</script>

</html>